package com.stedu.mall.goodsservice.controller;

import com.stedu.mall.common.bean.Comment;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.CommentService;
import com.stedu.mall.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @PostMapping
    public RespBean insert(@RequestBody Comment comment, @RequestHeader("token") String token) throws SteduException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");

        System.out.println(comment.toString());
        System.out.println("9988");
        comment.setUserId(userId);

//        if (commentService == null) {
//            System.out.println("commentService is null");
//            return RespBean.error("Service not initialized");
//        }

        try {
            commentService.insert(comment);
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈
            return RespBean.error("Insert failed: " + e.getMessage());
        }

        return RespBean.ok("评论成功！");
    }

    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id, @RequestHeader("token") String token) throws SteduException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        commentService.delete(id, userId);
        return RespBean.ok("删除评论成功！");
    }

    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") Integer id) {
        Comment comment = commentService.selectById(id);
        return RespBean.ok("", comment);
    }

    @GetMapping("/all")
    public RespBean selectByCondition(Comment condition) {
        List<Comment> comments = commentService.selectByCondition(condition);
        return RespBean.ok("", comments);
    }

}